package namespace

import (
	"context"
	"krm-backend/config"
	"krm-backend/controllers"
	"krm-backend/utils/logs"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type ResourceDetail struct {
	ResourceType string `json:"resourceType"`
	Total        int    `json:"total"`
}

func Detail(r *gin.Context) {
	logs.Debug(nil, "获取namespace资源详情")
	clientset, basicInfo, err := controllers.BasicInit(r, nil)
	returnData := config.ReturnData{}
	if err != nil {
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(200, returnData)
		return
	}
	_, err = clientset.CoreV1().Namespaces().Get(context.TODO(), basicInfo.Name, metav1.GetOptions{})
	if err != nil {
		msg := "获取Namespace资源详情失败" + err.Error()
		returnData.Message = msg
		returnData.Status = 400
		r.JSON(200, returnData)
		return
	}
	//查询资源的详情
	//pod
	podItems, _ := clientset.CoreV1().Pods(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	svcItems, _ := clientset.CoreV1().Services(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	cmItems, _ := clientset.CoreV1().ConfigMaps(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	secretItems, _ := clientset.CoreV1().Secrets(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	//deployment
	deployItems, _ := clientset.AppsV1().Deployments(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	dsItems, _ := clientset.AppsV1().DaemonSets(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	stsItems, _ := clientset.AppsV1().StatefulSets(basicInfo.Name).List(context.TODO(), metav1.ListOptions{})
	var totalMap map[string]int
	totalMap = make(map[string]int)
	totalMap["Pod"] = len(podItems.Items)
	totalMap["Deployment"] = len(deployItems.Items)
	totalMap["Service"] = len(svcItems.Items)
	totalMap["StatefulSet"] = len(stsItems.Items)
	totalMap["DaemonSet"] = len(dsItems.Items)
	totalMap["ConfigMap"] = len(cmItems.Items)
	totalMap["Secret"] = len(secretItems.Items)
	var namespaceDetail []ResourceDetail
	//统计 [resourceType]total
	for k, v := range totalMap {
		resourceDetail := ResourceDetail{
			ResourceType: k,
			Total:        v,
		}
		namespaceDetail = append(namespaceDetail, resourceDetail)
	}
	returnData.Message = "获取成功"
	returnData.Status = 200
	returnData.Data = make(map[string]interface{})
	returnData.Data["items"] = namespaceDetail
	r.JSON(200, returnData)
}
